﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Param = ClassLibrary.Parameters.Values;

namespace ClassLibrary
{
    public class MarkerDatasetConverter
    {
        public static bool Markers_To_DataSet( /*string server_Path,*/ /*List<string> categories, List<Marker> markerList*/)
        {
            StreamReader sr = null;
            StreamWriter sw = null;

            try
            {

                //if (null != markerFile && markerFile.Exists)
                {
                    //sr = new StreamReader(markerFile.FullName, System.Text.Encoding.UTF8);
                    //string pathtmp = Path.Combine(System.IO.Path.GetTempPath(), "dataset.js");
                    sw = new StreamWriter(Param.localPath_DataSet);

                    //************************************************************************
                    string line = File.ReadAllText(Param.localPath_DataSet_Base);
                    sw.Write(line);

                    //************************************************************************
                    sw.WriteLine(Param.DS_BEGIN_CAT);

                    //Diplay all
                    line = "listCategorie.push(\"";
                    line += Param.RM.GetString("DS_DisplayAll") + "\");";
                    sw.WriteLine(line);

                    //User custom cat
                    foreach (string cat in Param.Categories)
                    {
                        line = "listCategorie.push(\"";
                        line += cat + "\");";
                        sw.WriteLine(line);
                    }

                    //Uncategorized
                    line = "listCategorie.push(\"";
                    line += Param.RM.GetString("DS_Uncategorized") + "\");";
                    sw.WriteLine(line);

                    sw.WriteLine(Param.DS_END);

                    //************************************************************************
                    sw.WriteLine(Param.DS_BEGIN_Marker);

                    for (int i = 0; i < Param.MarkerList.Count; i++)
                    {
                        string lat = Param.MarkerList[i].lat.ToString();
                        lat = lat.Replace(",", ".");
                        string lng = Param.MarkerList[i].lng.ToString();
                        lng = lng.Replace(",", ".");
                        string titre = Param.DS_DIV_TITLE_O + Param.MarkerList[i].title + Param.DS_DIV_TITLE_C;
                        string img = string.Empty;
                        if (null != Param.MarkerList[i].Img_Medium)
                            img = Param.DS_DIV_IMG_O + /*server_Path+"//" +*/ Param.MarkerList[i].Img_Medium + Param.DS_DIV_IMG_C;
                        string description = string.Empty;

                        List<Event> list = Param.MarkerList[i].events;

                        foreach (Event d in list)
                        {
                            string link;
                            if (d.linkAsString != string.Empty) link = Param.DS_DIV_EVENT_LINK_O + d.linkAsString + Param.DS_DIV_EVENT_LINK_C;
                            else link = "<a>";
                            description += Param.DS_DIV_EVENT_O + d.dateString + " " + link + d.title + Param.DS_DIV_EVENT_C;
                        }
                        //string dateLien = "<div dir='ltr'>" + markerList[i].dateString + "<a href='" + markerList[i].lienAlbum + "'>" + markerList[i].comment + "</a></div>";
                        string icon = string.Empty;
                        if (null != Param.MarkerList[i].Img_Small)
                            icon = /*server_Path + "//" +*/ Param.MarkerList[i].Img_Small;

                        string lineMarker = "m = new Marker(" + lat + "," + lng + ",\"" + titre + img + description + "\",\"" + icon + "\");";
                        sw.WriteLine(lineMarker);

                        string cat = string.Empty;

                        if (Param.MarkerList[i].categories.Count == 0)
                            sw.WriteLine("m.cat.push(" + (Param.Categories.Count +1) + "); //"+Param.RM.GetString("DS_Uncategorized"));
                        else
                        {
                            foreach (string c in Param.MarkerList[i].categories)
                            {
                                int idx = Param.Categories.IndexOf(c);
                                sw.WriteLine("m.cat.push(" + (idx + 1) + "); //" + c); //idx + 1 because "display all" is the first one
                            }
                        }

                        sw.WriteLine(Param.DS_PUSH+"\n");

                    }
                    sw.WriteLine(Param.DS_END);
                    sw.Close();

                    return true;
                }
            }
            catch (Exception e)
            {
                ErrorManager.WriteLog("Makers_Management.cs", "Markers_To_DataSet", e);
                if (null != sr) sr.Close();
                if (null != sw) sw.Close();
                return false;
            }
        }

        public static bool Dataset_To_Marker(FileInfo Markerfile, out List<string> categories, out List<Marker> markers) 
        {
            bool RC = true;
            categories = new List<string>();
            markers = new List<Marker>();

            try
            {
                if (null != Markerfile && Markerfile.Exists)
                {
                    StreamReader sr = Markerfile.OpenText();
                    string line;
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine();
                        //CATEGORIE
                        if (line == Param.DS_BEGIN_CAT)
                        {
                            line = sr.ReadLine();
                            while (line != Param.DS_END)
                            {
                                int idx = line.IndexOf('\"') + 1;
                                line = line.Remove(0, idx);
                                idx = line.IndexOf('\"');
                                line = line.Remove(idx);
                                categories.Add(line);
                                line = sr.ReadLine();
                            }
                        }

                        //MARKEUR
                        if (line == Param.DS_BEGIN_Marker)
                        {
                            line = sr.ReadLine();
                            while (line != Param.DS_END)
                            {
                                int idx = line.IndexOf(Param.DS_NEW);
                                if (idx == 0)
                                {
                                    line = line.Replace(Param.DS_NEW+"(", "");
                                    line = line.Remove(line.Length - 2, 2);
                                    Marker m = DecodeDataSet(line);
                                    line = sr.ReadLine();
                                    while (line != Param.DS_PUSH)
                                    {
                                        int i1 = line.IndexOf('(');
                                        int i2 = line.IndexOf(')');
                                        int cat;
                                        string index = line.Substring(i1 + 1, i2 - i1 - 1);
                                        int.TryParse(index, out cat);
                                        if (cat >= 0 && cat < categories.Count)
                                            m.categories.Add(categories[cat]);
                                        line = sr.ReadLine();
                                    }

                                    if (null != m)
                                        markers.Add(m);
                                }

                                line = sr.ReadLine();
                            }
                        }
                    }
                }
                else RC = false;
            }
            catch (Exception e)
            {
                RC = false;
                ErrorManager.WriteLog("MarkerDatasetConverter", "Dataset_To_Marker", e);
            }
            return RC;
        }

        private static Marker DecodeDataSet(string line)
        {
            Marker m = new Marker();
            float lat = 0.0f, lng = 0.0f;
            string title = string.Empty, img_Med = string.Empty, img_Small = string.Empty;
            string local_Path_Med = string.Empty;
            string local_Path_Small = string.Empty;

            List<Event> eventList = new List<Event>();

            int idx;

            //lat
            idx = line.IndexOf(",");
            string latStr = line.Substring(0, idx);
            line = line.Substring(idx+1);
            latStr = latStr.Replace(".", ",");
            bool RC = float.TryParse(latStr, out lat);

            //Lng
            if (true == RC)
            {
                idx = line.IndexOf(",");
                string lngStr = line.Substring(0, idx);
                line = line.Substring(idx + 2);
                lngStr = lngStr.Replace(".", ",");
                RC = float.TryParse(lngStr, out lng);
            }

            //TITLE
            if (true == RC)
            {
                line = line.Substring(Param.DS_DIV_TITLE_O.Length);
                idx = line.IndexOf(Param.DS_DIV_TITLE_C);
                title = line.Substring(0, idx);
                line = line.Substring(idx + Param.DS_DIV_TITLE_C.Length);
            }
            //IMG MEDIUM
            if (true == RC)
            {
                line = line.Substring(Param.DS_DIV_IMG_O.Length);
                idx = line.IndexOf(Param.DS_DIV_IMG_C);
                img_Med = line.Substring(0, idx);
                //Remove http://...
                int idx2 = img_Med.IndexOf(Param.ServerRootFolder);
                if (-1 != idx2) img_Med = img_Med.Remove(0, idx2);
                
                line = line.Substring(idx + Param.DS_DIV_IMG_C.Length);

                string imgName = Path.GetFileName(img_Med);
                string imgLocalPath = Path.Combine(Param.localPath_Medium, imgName);
                if (File.Exists(imgLocalPath))
                    m.Img_Medium = imgName;
            }

            //EVENTS
            if (true == RC)
            {
                while (line.StartsWith(Param.DS_DIV_EVENT_O))
                {
                    string date, link, eventTitle, linkCode;
                    line = line.Substring(Param.DS_DIV_EVENT_O.Length);
                    idx = line.IndexOf(Param.DS_DIV_EVENT_LINK_O);
                    linkCode = Param.DS_DIV_EVENT_LINK_O;
                    if (-1 == idx)
                    {
                        linkCode = "<a>";
                        idx = line.IndexOf("<a>");
                    }
                    date = line.Substring(0, idx);
                    date = date.Replace("(", "");
                    date = date.Replace(")", "");

                    line = line.Substring(idx + linkCode.Length);

                    idx = line.IndexOf("'>");
                    link = line.Substring(0, idx);
                    line = line.Substring(idx + "'>".Length);

                    idx = line.IndexOf(Param.DS_DIV_EVENT_C);
                    eventTitle = line.Substring(0, idx);
                    line = line.Substring(idx + Param.DS_DIV_EVENT_C.Length);

                    Event e = new Event();
                    e.set(eventTitle, link, date);
                    eventList.Add(e);
                }
            }

            //IMG SMALL
            if (true == RC)
            {
                img_Small = line.Substring(3, line.Length - 4);
                int idx2 = img_Small.IndexOf(Param.ServerRootFolder);
                if (-1 != idx2) img_Small = img_Small.Remove(0, idx2);
            }

            //LOCAL PATH IMAGE MEDIUM 
            /*if (true == RC)
            {
                string img_Med_name = Path.GetFileName(img_Med);
                string imgLocalPath = Path.Combine(Param.localPath_Medium, img_Med_name);
                if (File.Exists(imgLocalPath))
                    m.Img_Medium = imgLocalPath;

            }

            //LOCAL PATH IMAGE SMALL
            if (true == RC)
            {
                string img_Small_name = Path.GetFileName(img_Small);
                string imgLocalPath = Path.Combine(Param.localPath_Small, img_Small_name);
                if (File.Exists(imgLocalPath))
                    m.Img_Small = imgLocalPath;

            }*/
            

            if (true == RC)
            {
                m.lat = lat;
                m.lng = lng;
                m.events = eventList;
                m.title = title;
                m.Img_Medium = img_Med;
                m.Img_Small = img_Small;
            }
            return m;
        }
    }
}
